package com.example.demoplus;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.example.demoplus.bean.UserBean;

import java.util.ArrayList;

/**
 * 数据库助手类
 * 创建数据库和增删改查工作
 */
public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String SWORD = "SWORD";
    /**
     * 声明一个数据库变量db
     * SQL lite是Android自带的数据库
     */
    private SQLiteDatabase db;

    /**
     * 构造方法
     * @param context
     * db_text:数据库名， 工厂默认空值，  版本号默认为从1开始
     */
    public DatabaseHelper(Context context){
        super(context,"db_text", null, 1);
    }
    /**
     * 创建数据库
     * @param db
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.i(SWORD, "create a Database: ");
//        创建数据库sql语句
        String sql = "CREATE TABLE IF NOT EXISTS user(id int PRIMARY KEY AUTOINCREMENT,name TEXT,password TEXT)";
//        执行创建数据库操作
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS user");
        onCreate(db);
    }
    /**
     * 自定义增删改查方法
     * add()
     * delete()
     * update()
     * getAllData()
     */
    public void add(String name, String password){
        db.execSQL("INSERT INTO user(name, password) VALUES(?,?)", new Object[]{name, password});
    }
    public void delete(String name, String password){
        db.execSQL("DELETE FROM user WHERE name = AND password = " + name + password);
    }
    public void update(String password){
        db.execSQL("UPDATE user SET password = ?", new Object[]{password});
    }
    /**
     * Cursor 游标，Android自带的数据库查询
     * @return ArrayList<UserBean>
     */
    public ArrayList<UserBean> getAllData(){
        ArrayList<UserBean> list = new ArrayList<>();
        Cursor cursor = db.query("user",null,null,null,null,null,null);
        while (cursor.moveToNext()){
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String password = cursor.getString(cursor.getColumnIndex("password"));
            list.add(new UserBean(name, password));
        }
        return list;
    }
}
